//参数传入月份为实际月份-1
var calendarTitleEl, calendar0, calendar1, calendar2, calendarDayList = [];
var calendarTodate, setYear, setMonthless;
var preCalendarIndex = 0;
var calendarUnlimitedSwiper = Swipe(document.getElementById('calendarUnlimited'), {
    callback: function(index, element) {
        changeCalendarDate(index, preCalendarIndex);
    },
});

function initCalendar (year, monthless) {
    calendarTitleEl = $api.byId('calendar-title');
    calendar0 = $api.byId('calendar-0');
    calendar1 = $api.byId('calendar-1');
    calendar2 = $api.byId('calendar-2');

    setYear = parseInt(year);
    setMonthless = parseInt(monthless);
    calendarTodate = getTodate();

    $api.text(calendarTitleEl, year + "年" + (monthless + 1) + "月");

    setDateCalendarSelecter(year, monthless, 0);
    switch(setMonthless)
    {
        case 0:
            setDateCalendarSelecter(year, 1, 1);
            setDateCalendarSelecter(year - 1, 11, 2);
            break;
        case 11:
            setDateCalendarSelecter(year + 1, 0, 1);
            setDateCalendarSelecter(year, 10, 2);
            break;
        default:
            setDateCalendarSelecter(year, monthless + 1, 1);
            setDateCalendarSelecter(year,monthless - 1, 2);
    }
}

//设置日期选择器日期
function setDateCalendarSelecter(year, monthless, temIndex) {
    var dom = $api.domAll('.calendar-line-' + temIndex);
    for (var d=0,lend=dom.length; d<lend; d++) {
        $api.remove(dom[d]);
    }

    var countDay = getCountDays(year, monthless);
    var startDayArray = getDateArray(year, monthless, 1);
    var calendarBlock, line = 0, lineBlock;
    switch(temIndex)
    {
        case 0:
            calendarBlock = calendar0;
            break;
        case 1:
            calendarBlock = calendar1;
            break;
        default:
            calendarBlock = calendar2;
    }

    if (startDayArray['weekless'] != 0) {
        $api.append(calendarBlock, '<div id="' + temIndex + "-" + line + '" class="' + "flex calendar-line-" + temIndex + '"></div>');
        lineBlock = $api.byId(temIndex + "-" + line);
        line++;
    }
    for (var e=0,lene=startDayArray['weekless']; e<lene; e++) {
        $api.append(lineBlock, '<div class="calendar-day"></div>');
    }
    for (var i=0,len=countDay; i<len; i++) {
        var temDateArray = getDateArray(year, monthless, i + 1);
        if (temDateArray['weekless'] == 0) {
            $api.append(calendarBlock, '<div id="' + temIndex + "-" + line + '" class="' + "flex calendar-line-" + temIndex + '"></div>');
            lineBlock = $api.byId(temIndex + "-" + line);
            line++;
        }
        if (temDateArray["date"] == calendarTodate) {
            temDateArray["day"] = "今日"
        }
        $api.append(lineBlock, '<div id="' + "c-" + temDateArray["date"] + '" class="flex calendar-day" tapmode onclick="selectCalendarDate(this)">' +
                '<div id="' + "b-" + temDateArray["date"] + '" class="calendar-day-block">' +
                    '<p id="' + "d-" + temDateArray["date"] + '" class="calendar-day-text">' + temDateArray["day"] + '</p>' +
                    '<div class="calendar-day-tag">' +
                        '<p id="' + "t-" + temDateArray["date"] + '"></p>' +
                    '</div>' +
                '</div>' +
            '</div>');
        // $api.append(lineBlock, '<div class="calendar-day-text" type="' + temDateArray["date"] + '" tapmode onclick="selectCalendarDate(this, '+ temIndex + ')">' + temDateArray["day"] + '</div>');
        // $api.append(lineBlock, '<p>' + temDateArray["day"] + '</p>');
    }

    if (temIndex == preCalendarIndex) {

    }
}

function changeCalendarDate(temIndex, temPreIndex) {
    var toSide, changeBlock;
    switch(temIndex)
    {
        case 0:
            if (temPreIndex == 1) {
                toSide = "-";
                changeBlock = 2;
                // setDay = setDay - 7;
                // setDateSelecter(setDay - 7, 2);
            } else {
                toSide = "+";
                changeBlock = 1;
                // setDay = setDay + 7;
                // setDateSelecter(setDay + 7, 1);
            }
            break;
        case 1:
            if (temPreIndex == 2) {
                toSide = "-";
                changeBlock = 0;
                // setDay = setDay - 7;
                // setDateSelecter(setDay - 7, 0);
            } else {
                toSide = "+";
                changeBlock = 2;
                // setDay = setDay + 7;
                // setDateSelecter(setDay + 7, 2);
            }
            break;
        case 2:
            if (temPreIndex == 0) {
                toSide = "-";
                changeBlock = 1;
                // setDay = setDay - 7;
                // setDateSelecter(setDay - 7, 1);
            } else {
                toSide = "+";
                changeBlock = 0;
                // setDay = setDay + 7;
                // setDateSelecter(setDay + 7, 0);
            }
            break;
    }
    if (toSide == "+") {
        switch(setMonthless)
        {
            case 11:
                setYear += 1;
                setMonthless = 0;
                break;
            default:
                setMonthless += 1;
        }
        switch(setMonthless)
        {
            case 11:
                setDateCalendarSelecter(setYear + 1, 0, changeBlock);
                break;
            default:
                setDateCalendarSelecter(setYear, setMonthless + 1, changeBlock);
        }
    } else {
        switch(setMonthless)
        {
            case 0:
                setYear -= 1;
                setMonthless = 11;
                break;
            default:
                setMonthless -= 1;
        }
        switch(setMonthless)
        {
            case 0:
                setDateCalendarSelecter(setYear - 1, 11, changeBlock);
                break;
            default:
                setDateCalendarSelecter(setYear, setMonthless - 1, changeBlock);
        }
    }
    haveCalendarTag();
    $api.text(calendarTitleEl, setYear + "年" + (setMonthless + 1) + "月");
    preCalendarIndex = temIndex;
}

function haveCalendarTag(temTagArray) {
    if (temTagArray != undefined) {
        calendarDayList = temTagArray;
    }

    // 清除所有标记
    var blockSelected = $api.domAll('.calendar-day-block-selected');
    var textSelected = $api.domAll('.calendar-day-text-selected');
    var textCanselect = $api.domAll('.calendar-day-text-canselect');
    var textWillselect = $api.domAll('.calendar-day-text-willselect');
    var tagSelected = $api.domAll('.calendar-day-tag-selected');
    var tagWillselect = $api.domAll('.calendar-day-tag-willselect');

    for (var a=0,lena=blockSelected.length; a<lena; a++) {
        $api.removeCls(blockSelected[a], 'calendar-day-block-selected');
    }
    for (var b=0,lenb=textSelected.length; b<lenb; b++) {
        $api.removeCls(textSelected[b], 'calendar-day-text-selected');
    }
    for (var c=0,lenc=textCanselect.length; c<lenc; c++) {
        $api.removeCls(textCanselect[c], 'calendar-day-text-canselect');
    }
    for (var d=0,lend=textWillselect.length; d<lend; d++) {
        $api.removeCls(textWillselect[d], 'calendar-day-text-willselect');
    }
    for (var e=0,lene=tagSelected.length; e<lene; e++) {
        $api.removeCls(tagSelected[e], 'calendar-day-tag-selected');
        $api.text(tagSelected[e], '');
    }
    for (var f=0,lenf=tagWillselect.length; f<lenf; f++) {
        $api.removeCls(tagWillselect[f], 'calendar-day-tag-willselect');
        $api.text(tagWillselect[f], '');
    }

    for (var g=0,leng=calendarDayList.length; g<leng; g++) {
        switch(calendarDayList[g]['status'])
        {
            case 0: //可以约
                $api.addCls($api.byId('d-' + calendarDayList[g]['date']), 'calendar-day-text-canselect');
                break;
            case 2: //约满
                $api.addCls($api.byId('t-' + calendarDayList[g]['date']), 'calendar-day-tag-willselect');
                $api.text($api.byId('t-' + calendarDayList[g]['date']), '约满');
                break;
            case 3: //已预约
                $api.addCls($api.byId('b-' + calendarDayList[g]['date']), 'calendar-day-block-selected');
                $api.addCls($api.byId('d-' + calendarDayList[g]['date']), 'calendar-day-text-selected');
                $api.addCls($api.byId('t-' + calendarDayList[g]['date']), 'calendar-day-tag-selected');
                $api.text($api.byId('t-' + calendarDayList[g]['date']), '已预约');
                break;
        }
    }
}

// function selectDate(el, week) {
//     // 移除上一选中样式
//     $api.removeCls($api.byId('d-'+selectData['date']), 'select-day');
//     if (haveClassArray.indexOf(selectData['date']) != -1) {
//         $api.addCls($api.byId('d-'+selectData['date']), 'class-day');
//     }
//
//     // 设置新的被选日期
//     var id = $api.attr(el,'id');
//     selectData['date'] = id.substring(2);
//     selectData['week'] = week;
//     $api.removeCls(el, 'class-day');
//     $api.addCls(el, 'select-day');
//     $api.text(dateSelectedEl, id.substring(2, 6)+"年"+id.substring(7, 9)+"月"+id.substring(10, 12)+"日");
//
//     if (classListBuffer == 0) {
//         if (classInfoData[selectData['week']]['data'] != undefined) {
//             getClassInfo(classInfoData[selectData['week']]['data']);
//         } else {
//             var classesEl = $api.byId("classes");
//             $api.remove(classesEl);
//             $api.append(body, '<div id="classes"></div>');
//         }
//     } else {
//         classInfoBuffer = 1;
//     }
// }
//
//
// function getClassList(temSetDay) {
//     // var classesEl = $api.byId("classes");
//     // $api.remove(classesEl);
//     // $api.append(body, '<div id="classes"></div>');
//     haveClassArray = [];
//     var temValues;
//     if (isShopowner == 1) {
//         temValues = {
//             store_id: storeId,
//             coach_id: teacherId,
//             start_date: fun_date(temSetDay)["date"],
//             end_date: fun_date(temSetDay + 6)["date"],
//         };
//     }  else {
//         temValues = {
//             store_id: storeId,
//             start_date: fun_date(temSetDay)["date"],
//             end_date: fun_date(temSetDay + 6)["date"],
//         };
//     }
//     classListBuffer = 1;
//     api.ajax({
//         url: apiUrl + '/v1/bespoke/list',
//         tag: '/v1/bespoke/list',
//         method: 'get',
//         data: {
//             values: temValues
//         }
//     }, function(ret, err) {
//         if (ret) {
//             if (ret.code == 200) {
//                 // alert(selectData['week'])
//                 if (ret.data.length != 0) {
//                     classInfoData = ret.data;
//                     // alert(selectData['week'])
//
//                     if (classInfoBuffer == 1 && (classInfoData.length != 0)) {
//                         if (classInfoData[selectData['week']]['type'] == 1) {
//                             getClassInfo(classInfoData[selectData['week']]['data']);
//                         }
//                     }
//                     for (var l=0,lenl=classInfoData.length; l<lenl; l++)
//                     {
//                         if (classInfoData[l]['type'] == 1) {
//                             haveClassArray.push(classInfoData[l]['date']);
//
//                         }
//                     }
//                     haveClassTag(haveClassArray);
//                 } else {
//                     haveClassTag([]);
//                     classInfoData = ret.data;
//                 }
//             } else {
//                 api.toast({
//                     msg: ret.msg,
//                     duration: 2000,
//                     location: 'middle'
//                 });
//             }
//         } else {
//             // api.alert({ msg: JSON.stringify(err) });
//         }
//         classInfoBuffer = 0;
//         classListBuffer = 0;
//     });
// }
//
// function getClassInfo(classInfoByDay) {
//     var classesEl = $api.byId("classes");
//     $api.remove(classesEl);
//     $api.append(body, '<div id="classes"></div>');
//     classesEl = $api.byId("classes");
//
//     if (classInfoByDay != undefined) {
//         for (var i=0,leni=classInfoByDay.length; i<leni; i++)
//         {
//             var stateClass, stateText, startTime, endTime;
//             switch(parseInt(classInfoByDay[i]["state"]))
//             {
//                 case 0:
//                     stateText = "待上课";
//                     stateClass = "class-hold";
//                     break;
//                 case 1:
//                     stateText = "上课中";
//                     stateClass = "class-begin";
//                     break;
//                 case 2:
//                     stateText = "待上课";
//                     stateClass = "class-hold";
//                     break;
//                 case 3:
//                     stateText = "已结束";
//                     stateClass = "class-end";
//                     break;
//             }
//             startTime = classInfoByDay[i]["start_time"];
//             endTime = classInfoByDay[i]["end_time"];
//
//             startTime = startTime.substring(0,startTime.length-3);
//             endTime = endTime.substring(0,endTime.length-3);
//
//             $api.append(classesEl,
//                 '<div id=' + "c-" + classInfoByDay[i]["id"] + ' style="width: 100%; height: 1.40rem; background-color: white; margin-bottom: 0.02rem;" tapmode onclick="openClassInfoWin(this)">' +
//                     '<div class="flex" style="width: 100%; height: 0.48rem; justify-content: space-between;">' +
//                         '<div style="width: 1.22rem; height: 0.26rem; border-top-right-radius:0.13rem; border-bottom-right-radius:0.13rem; background-color: rgba(216, 216, 216, 0.30); margin-top: 0.10rem">' +
//                             '<p style="line-height: 0.26rem; color: #333333; font-size: 0.14rem; font-weight:600; width: 100%; text-align: center;">'+ startTime + "-" + endTime +'</p>' +
//                         '</div>' +
//                         '<div class="' + stateClass + '">' + stateText + '</div>' +
//                     '</div>' +
//                     '<div  class="flex" style="width: 100%; height: 0.80rem; justify-content: space-between; align-items: center;">' +
//                         '<div class="flex" style="align-items: center;">' +
//                             '<div class="flex" style="width: 0.80rem; height: 0.80rem; border-radius: 0.40rem; background-color: rgba(216, 216, 216, 0.30); justify-content: center; align-items: center; margin-left: 0.13rem; margin-right: 0.10rem">' +
//                                 '<div style="width: 0.70rem; height: 0.70rem; border-radius:0.35rem; background-size: 0.70rem 0.70rem; background-image: url(' + apiImageUrl+ classInfoByDay[i]["order_image"] + ');"></div>' +
//                             '</div>' +
//                             '<div style="width: 2.33rem">' +
//                                 '<p style="font-size: 0.16rem; color: #333333; font-weight:900; line-height: 0.22rem; margin-bottom: 0.02rem">' + classInfoByDay[i]["curriculum_type_name"]  + " | " + classInfoByDay[i]["name"] + '</p>' +
//                                 '<p style="font-size: 0.12rem; color: #9B9B9B; line-height: 0.17rem;">' + classInfoByDay[i]["crowd"] + "/1v" + classInfoByDay[i]["number"] + '</p>' +
//                                 '<div class="flex" style="height: 0.25rem; align-items: center;">' +
//                                     '<div class="student-tag"></div>' +
//                                     '<p style="width: 2.14rem; font-size: 0.14rem; color: #666666; font-weight: 800; line-height: 0.25rem;">' + classInfoByDay[i]["courseChildren"] + '</p>' +
//                                 '</div>' +
//                             '</div>' +
//                         '</div>' +
//                         '<div class="flex" style="justify-content: center; align-items: center;">' +
//                             '<div class="arrow4"></div>' +
//                         '</div>' +
//                     '</div>' +
//                 '</div>');
//         }
//     }
// }
//
// //
// function openClassInfoWin(el) {
//     var id = $api.attr(el,'id');
//     var index = id.substring(2);
//     api.openWin({
//         name: 'classInfoWin',
//         url: './class/classInfoWin.html',
//         bgColor: '#ffffff',
//         vScrollBarEnabled: false, //是否显示垂直滚动条
//         hScrollBarEnabled: false, //是否显示水平滚动条
//         slidBackEnabled: true,
//         slidBackType: 'edge',
//         pageParam: {
//             course_id: index,
//         },
//         animation: {
//             type:"movein",
//             subType:"from_right",
//             duration:300
//         }
//     });
// }


function getCountDays(year, monthless) {
    var curDate = new Date();
    curDate.setFullYear(year, parseInt(monthless) + 1, 0);
    return curDate.getDate();
}

function getDateArray(year, monthless, day){
    var date = [];
    var temDate=new Date();
    temDate.setFullYear(year,monthless,day);

    var temweek = temDate.getDay();
    // if (temweek == 0){
    //     temweek = 6;
    // } else {
    //     temweek -= 1;
    // }

    date["weekless"] = temweek;
    date["week"] = temweek + 1;

    var temmonth = temDate.getMonth();
    date["monthless"] = temmonth;
    temmonth += 1;
    if (temmonth<10) {
        temmonth = "0" + temmonth;
    }
    date["month"] = temmonth;

    var temday = temDate.getDate();
    date["day"] = temday;
    if (temday<10) {
        temday = "0" + temday;
    }
    date["daystr"] = temday;

    date["year"] = year;
    date["date"] = year+"-"+temmonth+"-"+temday;

    return date;
}

function getTodate(){
    var date = new Date();

    var month = date.getMonth()+1;
    if (month<10) {
        month = "0" + month;
    }
    var day = date.getDate();
    if (day<10) {
        day = "0" + day;
    }
    var year = date.getFullYear();

    return year+"-"+month+"-"+day;
}